<?php


namespace app\common\lib\live;


use app\chat\LiveMessage as ChatLiveMessage;
use app\common\cachemodel\live\LiveRecordingInfo;
use app\common\cachemodel\live\LiveSignHotDay;
use app\common\cachemodel\live\LiveStatusDataRecord;
use app\common\lib\Util;
use think\Cache;
use think\Db;
use think\Log;
use think\queue\Job;
use XznsTools\cache\CacheManage;

class LiveCacheUpdateToDatabaseJob
{
    public function task(Job $job, $jobData)
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
            return;
        }

        switch ($jobData['type'])
        {
            case 'sign_hot_day':
                /**
                 * 'data' => [
                 * 'day' => $day,
                 * 'live_id' => $liveId,
                 * 'live_record_id' => $liveRecordId,
                 * ]
                 */
                $this->signHotDay($jobData['data']);
                break;
            case 'minute_status_data':
                /**
                 * $data = [
                 * 'time' => $time,
                 * 'live_id' => $liveId,
                 * ]
                 */
                // 获取最新的直播记录ID
                $liveRecordId = (new LiveRecordingInfo())->getNewestRecord($jobData['data']['live_id']);

                $this->minuteStatusData($jobData['data'], $liveRecordId);

                $liveRecordInfo = (new LiveRecordingInfo())->getInfoById($liveRecordId, ['status']);

                if ($liveRecordInfo['status'] == 1)
                {//直播状态  1=>直播中 2=>直播结束
                    Util::queuePush('live_cache_update_to_database', [
                        'type' => 'minute_status_data',
                        'data' => [
                            'time' => $jobData['data']['time'] + 60,
                            'live_id' => $jobData['data']['live_id'],
                        ],
                    ], 60);
                } else
                {
                    Cache::rm('live_cache_update_to_date:minute_status_data:' . $jobData['data']['live_id']);
                }
                break;
            case 'record_user_hot':
                /**
                 * $data = [
                 * 'date' => $date,
                 * 'uid' => $uid,
                 * 'live_id' => $liveId,
                 * 'live_record_id' => $liveRecordId,
                 * ]
                 */
                $this->recordUserHot($jobData['data']);
                break;
        }

        $job->delete();
    }

    public function signHotDay($data)
    {
        try
        {
            Cache::rm('live_cache_update_to_date:sign_hot_day:' . $data['live_id']);
            $time = time();
            $signHotDayModel = new LiveSignHotDay();
            $hotData = $signHotDayModel->where(['live_record_id' => $data['live_record_id'], 'day' => $data['day']])->column('id', 'sign');

            $hotDataNew = $signHotDayModel->getDaySignList($data['live_id'], $data['live_record_id'], $data['day']);

            for ($i = 1; $i <= 12; $i++)
            {
                if (isset($hotDataNew[$i]))
                {
                    if (isset($hotData[$i]))
                    {
                        $signHotDayModel->where('id', $hotData[$i])->update(['hot' => (int)$hotDataNew[$i]]);
                    } else
                    {
                        $insertData = [
                            'sign' => $i,
                            'hot' => (int)$hotDataNew[$i],
                            'live_id' => $data['live_id'],
                            'live_record_id' => $data['live_record_id'],
                            'day' => $data['day'],
                            'create_time' => $time
                        ];

                        $signHotDayModel->insert($insertData);
                    }
                }
            }

            return true;
        }
        catch (\Exception $e)
        {
            Log::write("直播间日榜热度同步数据库失败；错误消息：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);

            return false;
        }
    }

    private function minuteStatusData($data, $liveRecordId)
    {
        try
        {
            $date = date('YmdHi', $data['time']);

            $data['live_id'] = (int)$data['live_id'];
            $statusDataRecordModel = new LiveStatusDataRecord();
            $minuteStatusData = $statusDataRecordModel->getMinuteDatas($data['live_id'], $date);

            $hotData = $statusDataRecordModel->getHotNumData($data['live_id']);

            if ($minuteStatusData)
            {
                $insertData = [
                    'live_id' => $data['live_id'],
                    'live_record_id' => (int)$liveRecordId,
                    'time' => $date,
                    'zan_num' => (int)($minuteStatusData['zan_num'] ?? 0),
                    'comment_num' => (int)($minuteStatusData['comment_num'] ?? 0),
                    'gift_coin' => (int)($minuteStatusData['gift_coin'] ?? 0),
                    'gift_hot_num' => (int)($minuteStatusData['gift_hot_num'] ?? 0),
                    'online_user_num' => ChatLiveMessage::getClientIdCountByGroup($data['live_id'] . '_app_user_group'),
                    'total_hot' => $hotData['total_hot'],
                    'zan_hot' => $hotData['zan_hot'],
                    'gift_hot' => $hotData['gift_hot'],
                    'comment_hot' => $hotData['comment_hot'],
                ];
            } else
            {
                $insertData = [
                    'live_id' => $data['live_id'],
                    'live_record_id' => (int)$liveRecordId,
                    'time' => $date,
                    'zan_num' => 0,
                    'comment_num' => 0,
                    'gift_coin' => 0,
                    'gift_hot_num' => 0,
                    'online_user_num' => ChatLiveMessage::getClientIdCountByGroup($data['live_id'] . '_app_user_group'),
                    'total_hot' => $hotData['total_hot'],
                    'zan_hot' => $hotData['zan_hot'],
                    'gift_hot' => $hotData['gift_hot'],
                    'comment_hot' => $hotData['comment_hot'],
                ];
            }

            $statusDataRecordModel->insert($insertData);

            return true;
        }
        catch (\Exception $e)
        {
            Log::write("直播间每分钟热度信息同步数据库失败；错误消息：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);

            return false;
        }
    }

    private function recordUserHot($data)
    {
        try
        {
            Cache::rm('live_cache_update_to_date:record_user_hot:' . $data['live_id'] . ':' . $data['uid']);

            $cacheData = CacheManage::getInstance()->setCacheConfig('live.record_user_hot', "{$data['date']}:{$data['uid']}:{$data['live_record_id']}")->getCache();

            $liveUserHotData = Db::table('live_data.live_user_hot_' . $data['live_id'])->where(['uid' => $data['uid'], 'live_record_id' => $data['live_record_id'], 'date' => $data['date']])
                ->field('id')->find();

            if (!$liveUserHotData)
            {
                $d = [
                    'uid' => $data['uid'],
                    'live_record_id' => $data['live_record_id'],
                    'zan_hot' => (int)($cacheData['zan_hot'] ?? 0),
                    'message_hot' => (int)($cacheData['message_hot'] ?? 0),
                    'gift_hot' => (int)($cacheData['gift_hot'] ?? 0),
                    'date' => $data['date'],
                    'create_time' => time(),
                ];
                $d['total_hot'] = $d['zan_hot'] + $d['message_hot'] + $d['gift_hot'];


                Db::table('live_data.live_user_hot_' . $data['live_id'])->insert($d);
            } else
            {
                $d = [
                    'zan_hot' => (int)($cacheData['zan_hot'] ?? 0),
                    'message_hot' => (int)($cacheData['message_hot'] ?? 0),
                    'gift_hot' => (int)($cacheData['gift_hot'] ?? 0),
                ];

                $d['total_hot'] = $d['zan_hot'] + $d['message_hot'] + $d['gift_hot'];

                Db::table('live_data.live_user_hot_' . $data['live_id'])->where('id', $liveUserHotData['id'])->update($d);
            }

            return true;
        }
        catch (\Exception $e)
        {
            Log::write("直播间用户热度信息同步数据库失败；错误消息：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);

            return false;
        }
    }
}
